import React, { Fragment, useEffect, useState } from 'react';
import { ColumnProps, PaginationConfig, SorterResult } from 'antd/es/table';
import { Badge, Button, Card, Divider, Form, message, Popconfirm, Table, Upload, Icon } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import styles from '@/utils/table.less';
import { MenuItem } from './data.d';
import { Dispatch } from '@/models/connect';
import encodeQueryParam from '@/utils/encodeParam';
import Save from './save';
import apis from '@/services';
import { downloadObject } from '@/utils/utils';
import { FormComponentProps } from 'antd/lib/form';
import moment from 'moment';
import SearchForm from '@/components/SearchForm';

interface Props extends FormComponentProps {
  dispatch: Dispatch;
  location: Location;
  loading: boolean;
}

interface State {
  data: any;
  tenantList: any;
  searchParam: any;
  saveVisible: boolean;
  current: Partial<MenuItem>;
}

const SqlRuleList: React.FC<Props> = props => {

  const initState: State = {
    data: [],
    searchParam: {
      pageSize: 10,
      pageIndex: 0, 
    },
    saveVisible: false,
    current: {},
    tenantList: [],
  };

  const [searchParam, setSearchParam] = useState(initState.searchParam);
  const [saveVisible, setSaveVisible] = useState(initState.saveVisible);
  const [current, setCurrent] = useState(initState.current);
  const [data, setData] = useState(initState.data);
  const [tenantList, setTenantList] = useState(initState.tenantList);
  const [loading, setLoading] = useState(false);

  const handleSearch = (params?: any) => {
    setSearchParam(params);
    apis.menu.list(encodeQueryParam(params))
      .then(response => {
        if (response.status === 200) {
          setData(response.result);
          console.log('data',data)
        }
      })
      .catch(() => {
      });
  };

  useEffect(() => {
    handleSearch(searchParam);
    apis.menu.queryNoPaging({}).then(res => {
      if (res.status === 200) {
        let data = res.result
        let params = {
          id: 'all',
          name: 'all'
        }
        let params1 = {
          id: 'admin',
          name: 'admin'
        }
        data.unshift(params1)
        data.unshift(params)
        setTenantList(data);
      }
    })
  }, []);

  const edit = (record: MenuItem) => {
    setCurrent(record);
    setSaveVisible(true);
  };

  const handleDelete = (record: MenuItem) => {
    let parms = {
      menuId: record.menuId,
      tenantId: record.tenantId
    }
    apis.menu.remove(parms)
      .then(response => {
        if (response.status === 200) {
          message.success('删除成功');
          handleSearch(searchParam);
        }
      })
      .catch(() => {
      });
  };

  const saveOrUpdate = (item: MenuItem) => {
    setLoading(true)
    apis.sqlRule.saveOrUpdate(item)
      .then((response: any) => {
        if (response.status === 200) {
          message.success('保存成功');
        }
      })
      .catch(() => {
      }).finally(() => {
        setLoading(false)
      });
  };


  const columns: ColumnProps<MenuItem>[] = [
    {
      title: '菜单Id',
      dataIndex: 'menuId',
    },
    {
      title: '菜单名称',
      width: '120px',
      dataIndex: 'menuName',
    },
    {
      title: '租户Id',
      width: '160px',
      dataIndex: 'tenantId',
    },
    {
      title: '租户名称',
      width: '120px',
      dataIndex: 'tenantName',
    },
    {
      title: '大屏Id',
      width: '150px',
      dataIndex: 'screenId',
    },
    {
      title: '大屏名称',
      dataIndex: 'screenName',
    },
    {
      title: '操作',
      width: '130px',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => edit(record)}>编辑</a>
          <Divider type="vertical" />
          <Popconfirm title="确认删除?" onConfirm={() => handleDelete(record)}>
            <a>删除</a>
          </Popconfirm>
        </Fragment>
      ),
    },
  ];

  const onTableChange = (
    pagination: PaginationConfig,
    filters: any,
    sorter: SorterResult<MenuItem>,
  ) => {
    handleSearch({
      pageIndex: Number(pagination.current) - 1,
      pageSize: pagination.pageSize,
      terms: searchParam,
      sorts: sorter,
    });
  };

  return (
    <PageHeaderWrapper title="对应菜单">
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div>
            <SearchForm
              search={(params: any) => {
                let param = params;
                if (!param) param = {};
                handleSearch({
                  terms: param, pageSize: 10, pageIndex: data.pageIndex, 
                });
              }}
              formItems={[{
                label: '菜单Id',
                key: 'menuId',
                type: 'string',
              },
              {
                label: '租户',
                key: 'tenantId',
                type: 'list',
                props: {
                  data: tenantList,
                  mode: 'tenant',
                },
              }]}
            />
          </div>
          <div className={styles.tableListOperator}>
            <Button
              icon="plus"
              type="primary"
              onClick={() => {
                setCurrent({});
                setSaveVisible(true);
              }}
            >
              新建
            </Button>
          </div>
          <div className={styles.StandardTable}>
            <Table
              loading={props.loading}
              dataSource={data?.data}
              columns={columns}
              rowKey="id"
              onChange={onTableChange}
              pagination={{
                current: data.pageIndex + 1,
                total: data.total,
                pageSize: data.pageSize,
                showQuickJumper: true,
                showSizeChanger: true,
                pageSizeOptions: ['10', '20', '50', '100'],
                showTotal: (total: number) =>
                  `共 ${total} 条记录 第  ${data.pageIndex + 1}/${Math.ceil(
                    data.total / data.pageSize,
                  )}页`,
              }}
            />
          </div>
        </div>
      </Card>
      {saveVisible && (
        <Save
          data={current}
          close={() => {
            setSaveVisible(false);
            setCurrent({});
          }}
          save={(item: MenuItem) => {
            setSaveVisible(false);
            handleSearch(searchParam);
          }}
        />
      )}
    </PageHeaderWrapper>
  );
};
export default Form.create<Props>()(SqlRuleList);
